﻿using BarcodeDelay.bean;
using BarcodeDelay.utility;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class CuiJianMessageHelper
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListDepBarcodes = new ArrayList();
        public event Action DoneHttpResponse;
        public event Action GotInterceptBarcode;
        private string m_strCurBarcode = "";
        ArrayList m_arListBarcodes = new ArrayList();
        private bool isInProcess = false;
        ArrayList arListArbitrationBarcodes = new ArrayList();
        private static CuiJianMessageHelper instance;
        public static CuiJianMessageHelper Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new CuiJianMessageHelper();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        public void BeginAnalyThread(ArrayList  arListBarcodes, string anayType)
        {
            try
            {
                m_arListBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }

                m_arListBarcodes = arListBarcodes;
                //m_arListDepBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ThreadStart(handleAllBarcodes));//出港分析 开辟一个新的线程
                fThreadDep.IsBackground = true;
                fThreadDep.Start();

            }
            catch (Exception ex)
            {

            }
        }

        private void handleAllBarcodes()
        {
            try
            {
                string outmsg = "";
                if(arListArbitrationBarcodes.Count==0)
                {
                    arListArbitrationBarcodes = JTDelayHelper.Instance.getArbitrationBarcodes(out outmsg);
                }
                

                isInProcess = true;
                foreach(string strBarcode in m_arListBarcodes)
                {
                    System.Threading.Thread.Sleep(200);
                    if(strBarcode.Length<10)
                    {
                        continue;
                    }

                    if(arListArbitrationBarcodes.Contains(strBarcode))
                    {
                        StoParams.Instance.interResMsg = strBarcode+ " 已申请过仲裁";
                        DoneHttpResponse();
                        continue;
                    }

                    string outMsg = "";
                    string lastUpdateTime = "";
                    /*JTDelayHelper.Instance.getCommentsContent(strBarcode, out outMsg, out lastUpdateTime);

                    if (outMsg.Contains("已理赔"))
                    {
                        StoParams.Instance.interResMsg = strBarcode + " 已理赔";
                        DoneHttpResponse();
                        continue;
                    }*/

                    m_strCurBarcode = strBarcode;
                    StoParams.Instance.interResMsg = "";
                    ArrayList arListAllGXTask = new ArrayList();
                    string httpRes = "";
                    ArrayList arListRoadMap = JTDelayHelper.Instance.getRoadMap(strBarcode, out httpRes, arListAllGXTask);
                    if (arListRoadMap.Count == 0)
                    {
                        StoParams.Instance.interResMsg = "未授权";
                        Thread.Sleep(300);
                        DoneHttpResponse();
                        continue;

                    }
                   
                    string problemType = "";
                    outMsg = "";
                    string commentType = "";
                    string strInterCeptSiteCode = "";
                    /*if(JTDelayHelper.Instance.isInterceptDelay(arListRoadMap))
                    {
                        StoParams.Instance.interBarcode = strBarcode;
                        GotInterceptBarcode();

                        bool resAddCommnetIntercept = addComment(m_strCurBarcode, commentType);
                        if (resAddCommnetIntercept)
                        {                           
                            StoParams.Instance.interBarcode = m_strCurBarcode;
                        }
                        else
                        {
                            if (StoParams.Instance.interResMsg == "")
                            {
                                StoParams.Instance.interResMsg = "留言失败";
                            }

                        }
                        StoParams.Instance.interResMsg = m_strCurBarcode + "\r\n" +"超时未退回"+ "\r\n" + StoParams.Instance.interResMsg;
                        DoneHttpResponse();
                        Thread.Sleep(300);
                        continue;
                    }*/

 
                    string siteName = "";
                    string leaveMsg = "";
                    //bool isDelay = JTDelayHelper.Instance.parseInterceptBarcode(arListRoadMap, out commentType, out strInterCeptSiteCode,out siteName);
                    JTDelayHelper.Instance.parseManualBarcode(arListRoadMap, out commentType, out strInterCeptSiteCode, out siteName,out leaveMsg);

                    if (strInterCeptSiteCode == "")
                    {
                        StoParams.Instance.interResMsg = "已签收";
                        DoneHttpResponse();
                        continue;
                    }


                    StoParams.Instance.interResMsg = "";
                    /*bool resAddCommnet = addComment(m_strCurBarcode, commentType);
                    if (resAddCommnet)
                    {
                       
                        StoParams.Instance.interBarcode = m_strCurBarcode;
                    }
                    else
                    {
                        if (StoParams.Instance.interResMsg == "")
                        {
                            StoParams.Instance.interResMsg = "留言失败";
                        }

                    }*/
                    StoParams.Instance.interResMsg = m_strCurBarcode + "\r\n" + StoParams.Instance.interResMsg;
                    DoneHttpResponse();
                    Thread.Sleep(300);
                    cuiParcel(m_strCurBarcode, out outMsg, strInterCeptSiteCode, siteName);
                    StoParams.Instance.interResMsg = outMsg;
                    DoneHttpResponse();
                    Thread.Sleep(300);
                    /*StoParams.Instance.interResMsg = "刷新登记信息，等待五秒钟自动拦截";
                    DoneHttpResponse();
                    Thread.Sleep(5000);
                    bool resInter = interceptProblemParcel(arListRoadMap, m_strCurBarcode, out outMsg);
                    if (resInter)
                    {
                        StoParams.Instance.interResMsg = "拦截成功";
                    }
                    else
                    {
                        StoParams.Instance.interResMsg = outMsg;
                    }
                    DoneHttpResponse();
                    Thread.Sleep(300);
                    if(!resInter&& !outMsg.Contains("运单已签收"))
                    {
                        StoParams.Instance.interResMsg = "第一次拦截失败，等待六秒钟再次自动拦截";
                        Thread.Sleep(6000);
                        resInter = interceptProblemParcel(arListRoadMap, m_strCurBarcode, out outMsg);
                        if (resInter)
                        {
                            StoParams.Instance.interResMsg = "拦截成功";
                        }
                        else
                        {
                            StoParams.Instance.interResMsg = outMsg;
                        }
                        DoneHttpResponse();
                        Thread.Sleep(300);
                    }*/
          
                }               
                
            }
            catch(Exception ex)
            {
                isInProcess = false;
                StoParams.Instance.resMsg = "请求失败，请重新登录";
                DoneHttpResponse();
            }
            isInProcess = false;
        }

        private bool interceptProblemParcel(ArrayList arListRoadMap, string strCurBarcode,out string msg)
        {
            msg = "";
            bool res = false;
            try
            {
                string strUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/rebackTransferExpress/getBatchRebackWaybill";
                JObject jObj = new JObject();

                JArray jarry = new JArray();
                jObj["current"] = 1;
                jObj["size"] = 20;
                jObj["countryId"] = "1";
                jObj["applyTypeCode"] = 3;
                jarry.Add(strCurBarcode);
                jObj["waybillIds"] = jarry;
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, "returnAndForwardMaintain");
                if (!resMsg.Contains("请求成功"))
                {
                    msg = "请求失败";
                    return false;
                }
                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JArray records = (JArray)jsonObjRes["data"];
                if (records.Count == 0)
                {
                    msg = strCurBarcode + " 查询失败,跳过拦截环节";
                    return false;
                }
                strUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/rebackTransferExpress/addRebackExpress";
                jObj = new JObject();
                jObj["countryId"] = "1";
                jObj["applyTypeCode"] = 3;
                jObj["waybillNo"] = strCurBarcode;
                postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                resMsg = HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, "returnAndForwardMaintain");
                if (!resMsg.Contains("请求成功"))
                {
                    jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                    JToken msgToke = jsonObjRes["msg"];
                    msg = "拦截失败:"+ msgToke.ToString();
                    return false;
                }
                else
                {
                    msg = "拦截成功";
                    res = true;
                    return true;
                }
                //jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
            }
            catch (Exception ex)
            {

            }


            return res;
        }

        private bool cuiParcel(string strCurBarcode,out string msg,string strInterCeptSiteCode,string siteName)
        {
            msg = "";
            bool res = false;
            try
            {
                //string strUrl = "https://jmsgw.jtexpress.com.cn/basicdata/network/select/all?current=1&size=100&name=" + strInterCeptSiteCode + "&typeIds%5B0%5D=336&queryLevel=3";
                string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/problemPiece/getPageByName?current=1&size=10&queryLevel=3&name="  + siteName;
                JObject jObj = new JObject();
                JArray jarry = new JArray();

                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "batchProblem");
                if(!resMsg.Contains("请求成功"))
                {
                    msg = "催件失败 "+ resMsg;
                    return false;
                }
                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JObject jsonObjData = (JObject)jsonObjRes["data"];
                JArray records = (JArray)jsonObjData["records"];
                if(records.Count==0)
                {
                    msg = "网点："+ siteName + " 不存在,跳过催件环节";
                    return false;
                }
                string signStieCode = "";
                int receiveNetworkId = 0;
                for (int i=0;i< records.Count;i++)
                {
                    JObject json = (JObject)records[i];
                    JToken code = json["code"];
                    JToken id = json["id"];
                    if (code!=null)
                    {
                        if(id.ToString() == strInterCeptSiteCode)
                        {
                            signStieCode = code.ToString();
                            if(id!=null)
                            {
                                receiveNetworkId = Convert.ToInt32(id);
                            }
                            break;
                        }
                    }
                }
                if(signStieCode==""|| receiveNetworkId==0)
                {
                    msg = "网点：" + siteName + " 不存在,无法催件";
                    return false;
                }
                strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/problemPiece/registration";
                string routerName = "batchProblem";
                jObj = new JObject();
                jObj["countryId"] = "1";
                jObj["defaultKnow"] = null;
                jObj["firstLevelTypeName"] = "催件";
                jObj["knowNetwork"] = "";
                jObj["paths"] = "";
                jObj["probleDescription"] = MemberInfo.Instance.templeteCuijian;
                jObj["probleTypeId"] = 1;
                jObj["probleTypeSubjectId"] = 100123;
                jObj["probleTypeSubjectId2"] = 100124;
                jObj["problemPieceId"] = "";
                jObj["problemTypeSubjectCode"] = "50";
                jObj["receiveNetworkId"] = receiveNetworkId;
                jObj["replyContent"] = "";
                jObj["replyContentImg"] = new JArray();
                jObj["replyStatus"] = 0;
                jObj["secondLevelTypeCode"] = "50a";
                jObj["secondLevelTypeId"] = 100124;
                jObj["secondLevelTypeName"] = "催件a";
                jObj["uploadDataProp"] = "";
                jObj["waybillNo"] = strCurBarcode;
                postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);

                resMsg = HttpClient.HttpUtil.Instance.PostCommon(strUrl, postData, routerName);
                if (!resMsg.Contains("请求成功"))
                {
                    jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                    JToken msgToke = jsonObjRes["msg"];

                    msg = "催件失败:"+ msgToke.ToString();
                    return false;
                }
                else
                {
                    msg = "催件成功";
                    return true;
                }

            }
            catch(Exception ex)
            {

            }

            
         
            return res;
        }

        private bool addComment(string strBarCode,string commentType)
        {
            
            bool ret = false;
            try
            {
                string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/leaveMessage/getReceiveNetwork?waybillNo=" + strBarCode.Trim();
                JObject jObj = new JObject();
                JArray jarry = new JArray();
                jarry.Add(strBarCode);

                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string res = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "integratedQuery");
                /*if (!res.Contains("请求成功"))
                {
                    if (res.Contains("msg"))
                    {
                        JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(res);
                        JToken msgToken = jsonObjRes["msg"];
                        StoParams.Instance.interResMsg = msgToken.ToString();
                    }
                    else
                    {
                        StoParams.Instance.interResMsg = res.ToString();
                    }
                    //QueryMessageRes.Invoke();
                    return ret;
                }*/
                string msg = "";
                ArrayList arListRoadMap = new ArrayList();
                ArrayList arListRoadGX = new ArrayList();
                arListRoadMap = JTDelayHelperNew.Instance.getRoadMap(strBarCode.Trim(), out msg, arListRoadGX);
                SiteBean siteBean = UtilityHelp.Instance.getFirstSite(res, arListRoadMap);
                if (siteBean.siteCode == "")
                {
                    siteBean = UtilityHelp.Instance.getBeanSite(arListRoadMap);
                }
                //SiteBean siteBean = UtilityHelp.Instance.getLastSite(res);

                if (siteBean.siteCode == "")
                {
                    return ret;
                }
                if (StoParams.Instance.register_site.Contains(siteBean.siteName.Trim())
                    || siteBean.siteName.Trim().Contains(StoParams.Instance.register_site))
                {
                    return ret;
                }
                jObj["waybillNo"] = strBarCode.Trim();
                jObj["receiveNetworkId"] = siteBean.siteId.Trim();
                jObj["fileUrl"] = "";
                jObj["receiveNetworkName"] = siteBean.siteName.Trim();
                jObj["receiveNetworkCode"] = siteBean.siteCode.Trim();
                jObj["countryId"] = "1";
                jObj["leaveMessageType"] = 3;
                //string tmplete = "此件已退款，商家急催要求尽快退回";
                string tmplete = MemberInfo.Instance.templeteReturn;
               /*if(commentType=="")
               {
                   commentType = "中转";
               }
               if(commentType.Contains("中转"))
               {
                   tmplete = MemberInfo.Instance.templeteTransfer;
               }
               else if (commentType.Contains("派件"))
               {
                   tmplete = MemberInfo.Instance.templeteAssign;
               }
               else if (commentType.Contains("签收"))
               {
                   tmplete = MemberInfo.Instance.templeteQS;
               }*/
               jObj["replyContent"] = tmplete;
                //string postUrl = "https://jmsgw.jtexpress.com.cn/servicequality/leaveMessage/add";

                string postUrl = "https://jmsgw.jtexpress.com.cn/operatingplatform/messageBoard/add";
                postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);

                //return;
                string messge = HttpClient.HttpUtil.Instance.addLeaveMessage(postUrl, postData);
                if (messge.Contains("成功"))
                {
                    ret = true;
                    StoParams.Instance.interResMsg = "留言成功-"+ siteBean.siteName;
                }
                else
                {
                    JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(messge);
                    JToken msgToken = jsonObjRes["msg"];
                    string msgStr = "";
                    if(msgToken!=null)
                    {
                        msgStr = msgToken.ToString();
                    }
                    StoParams.Instance.interResMsg = "留言失败-" + siteBean.siteName+" "+ msgStr;
                }
            }
            catch(Exception ex)
            {

            }
            return ret;
        }

      

        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadDep.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }

    
            }
            catch (Exception ex)
            {

            }
        }


        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
